import {
	base64encode
} from '@/static/js/Base64.js';
import {
	recordOpenApp
} from '@/api/index.js';
// -防抖
export function debounce(fn, wait) {
	let delay = wait || 500
	let timer
	return function() {
		let args = arguments;
		if (timer) {
			clearTimeout(timer)
			console.log('拦截')
		}
		let callNow = !timer
		timer = setTimeout(() => {
			console.log('发送')
			timer = null
		}, delay)
		if (callNow) fn.apply(this, args)
	}
}

// -节流
export function throttle(fn, wait) {
	let delay = wait || 500
	let timer = null
	let firstTime = true
	return function() {
		if (timer) {
			console.log('拦截');
			return
		}
		if (firstTime) {
			fn.apply(this, arguments)
			firstTime = false
			return
		}
		timer = setTimeout(() => {
			console.log('发送');
			fn.apply(this, arguments)
			timer = null
		}, delay)
	}
}

// 去除前后空格
export function strTrim(str) {
	let text = str
	if (str) {
		text = str.trim()
	}
	// const text = str.replace(/^\s+|\s+$/g,"")
	return text
}
// 跳转 url:跳转路径, data:路径参数, type: 类型, callback: boolean回调 debounce throttle
export const pageTo = debounce((url, data, type, callback) => {
	let pathType = type || ''
	if (url == '/index/index') {
		pathType = 'switchTab'
	}
	let pathUrl = url
	const bw_link = getApp().getBWData(['bw_link']).bw_link
	if (bw_link.link && !pathUrl.includes('?')) {
		pathUrl = pathUrl + '?bwlink=' + bw_link.link
	} else if (bw_link.link) {
		pathUrl = pathUrl + (bw_link.link ? '&bwlink=' + bw_link.link : '')
	}
	// 如果跳转登录是存在link的情况存入跳转登录前的链接 //  && bw_link.link
	// #ifdef H5
	if (url == '/mine/mobile') {
		bw_link.loginSource = window.location.href
		uni.setStorageSync('bw_link', JSON.stringify(bw_link))
	}
	// #endif
	if (typeof(data) !== 'string') {
		// 处理传参
		if (!pathUrl.includes('?')) {
			pathUrl = pathUrl + "?"
		} else {
			pathUrl = pathUrl + "&"
		}
		for (var k in data) {
			if (typeof(data[k]) == "object") {
				data[k] = JSON.stringify(data[k]);
			}
			pathUrl += k + "=" + encodeURIComponent(data[k]) + "&";
		}
		pathUrl = pathUrl.substring(0, pathUrl.length - 1);
	} else {
		pathType = data
	}
	console.log(pathUrl)
	if (pathType == 'navigateBack' || url == 'navigateBack') {
		if (data && data.params) {
			let pages = getCurrentPages() // 当前页面
			let prevPage = pages[pages.length - 2] // 上一页面
			let params = JSON.parse(data.params)
			prevPage.setData(params)
		}
		// 关闭当前页面，返回上一页面或多级页面
		uni.navigateBack({
			delta: data ? data.delta : 1,
			fail: () => {
				// 如果返回上一页没有那么跳转至考生首页
				wx.switchTab({
					url: '/index/index'
				})
			}
		})
	} else if (pathType == 'switchTab') {
		// 跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
		uni.switchTab({
			url: pathUrl
		})
	} else if (pathType == 'reLaunch') {
		// 关闭所有页面，打开到应用内的某个页面
		uni.reLaunch({
			url: pathUrl
		})
	} else if (pathType == 'redirectTo') {
		// 关闭当前页面，跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面
		uni.redirectTo({
			url: pathUrl
		})
	} else {
		// 保留当前页面，跳转到应用内的某个页面。但是不能跳到 tabbar 页面
		uni.navigateTo({
			url: pathUrl,
			fail(err) {
				if (callback) {
					callback(false)
				}
			},
			success(res) {
				if (callback) {
					callback(true)
				}
			}
		})
		// this.$router.push(pathUrl)
	}
}, 1000)

export const getRequest = (str, name) => {
	var reg = new RegExp('(^|\\?|&)' + name + '=([^&]*|$)'); //正则表达式
	var url = str.replace(/&/g, '&');
	var r = url.match(reg);
	return r === null ? null : decodeURI(r[2]);
}

export const parseQueryStringt = (url) => {
	// 编写代码实现
	// 1.查找?的下标
	var index = url.indexOf("?");
	// 2.截取?后面的字符串
	var str = url.slice(index + 1);
	// 3.根据&将字符串转成数组
	var arr = str.split("&");

	// 4. 声明对象用来存储信息
	var obj = {};
	for (var i = 0; i < arr.length; i++) {
		// arr[0] action=home
		var arr2 = arr[i].split('=');
		// arr2的第一个成员做属性, 第二个成员做值
		obj[arr2[0]] = arr2[1];
	}
	return obj;
}

export const timestampToTime = (timestamp, format) => {
	//   timestamp = timestamp.length == 10 ? timestamp * 1000 : timestamp
	//   var date = new Date(Number(timestamp)); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var date = new Date(Number(timestamp));
	var Y = date.getFullYear();
	var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
	var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
	var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
	var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
	var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
	if (format == 'YMD') {
		return Y + '-' + M + '-' + D
	} else if (format == 'YM') {
		return Y + '-' + M;
	} else {
		return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s;
	}
}
export const getDate = (type, num) => {
	const date = new Date();
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let day = date.getDate();

	if (type === 'start') {
		year = year - num;
	} else if (type === 'end') {
		year = year - num;
	} else if (type === 'maxEnd') {
		year = year + num;
	}
	month = month > 9 ? month : '0' + month;
	day = day > 9 ? day : '0' + day;
	const newDate = `${year}-${month}-${day}`;
	console.log(newDate)
	return new Date(newDate).getTime();
}
export const getMymethod = (birthday, type) => { //根据日期算年龄
	if (birthday) {
		birthday = birthday.split('-');
		// 新建日期对象
		let date = new Date();
		// 今天日期，数组，同 birthday
		let today = [date.getFullYear(), date.getMonth() + 1, date.getDate()];
		// 分别计算年月日差值
		let age = today.map((val, index) => {
			return val - birthday[index]
		})
		// 当天数为负数时，月减 1，天数加上月总天数
		if (age[2] < 0) {
			// 简单获取上个月总天数的方法，不会错
			let lastMonth = new Date(today[0], today[1], 0)
			age[1]--
			age[2] += lastMonth.getDate()
		}
		// 当月数为负数时，年减 1，月数加上 12
		if (age[1] < 0) {
			age[0]--
			age[1] += 12
		}
		if (type == 'Y') {
			return age[0] + '岁'
		}
		if (type == 'YM') {
			return age[0] + '岁' + age[1] + '月'

		}
		if (type == 'YMS') {
			return age[0] + '岁' + age[1] + '月' + age[2] + '天'

		}
	}
}

export function unitNum(value) {
	// console.log(value)
	if (typeof(value) == 'number') {
		value = value / 1000 + 'K';
	}
	return value
}
// 日期转换
export const dateFormat = (date) => {
	let text = ''
	const curDate = new Date()
	const oldDate = new Date(date)
	const curTime = curDate.getTime() / 1000
	const oldTime = oldDate.getTime() / 1000
	const month = oldDate.getMonth() + 1
	const day = oldDate.getDate()
	if (curTime - oldTime < 60) {
		text = '刚刚' // 小于一分钟是刚刚
	} else if (curTime - oldTime < 3600) {
		text = parseInt((curTime - oldTime) / 60) + '分钟前' // 一小时内
	} else if (curTime - oldTime < 3600 * 24) {
		text = parseInt((curTime - oldTime) / 3600) + '小时前' // 24小时内
	} else if (curTime - oldTime < 3600 * 24 * 2) {
		text = '昨天' // 48小时内
	} else if (curDate.getFullYear() - oldDate.getFullYear() == 0) {

		text = (month < 10 ? '0' + month : month) + '月' + (day < 10 ? '0' + day : day) + '日' // 是否是当年
	} else {
		text = oldDate.getFullYear() + '年' + (month < 10 ? '0' + month : month) + '月' + (day < 10 ? '0' + day :
			day) + '日' // 小于一分钟是刚刚
	}
	return text
}
// 判断h5是否登录
export function judgeIsLogin() {
	const bw_params = JSON.parse(uni.getStorageSync('bw_params') || '{}');
	const bw_user_temp = JSON.parse(uni.getStorageSync('bw_user_temp') || '{}');
	if (bw_params && bw_params.access_token && bw_user_temp && bw_user_temp.memberId) {
		return true;
	} else {
		return false;
	}
}
// 判断备考生是否登录
export function getTokenStatus() {
	const bw_bks_params = uni.getStorageSync('bw_bks_params') || '';
	if (bw_bks_params.access_token) {
		return true
	} else {
		return false
	}

}
// openinstall 唤起app
export function openAppULinkNew(id, data, urlAndroid, selector) {
	recordOpenApp({
		"clickLink": window.location.href,
		"promoteContent": data,
		sharerId: data.sharerId
	})
	var data = OpenInstall.parseUrlParams(); //js中提供的api，解析当前网页url中的查询参数并对data进行赋值
	// data.href = window.location.href
	new OpenInstall({ //初始化方法，与openinstall服务器交互，应尽早调用
		appKey: "hfans1", //appKey为openinstall为应用分配的唯一id（必须传入）
		onready: function() { //初始化成功回调方法。当初始化完成后，会自动进入
			this.schemeWakeup(); //尝试使用scheme打开App（主要用于Android以及iOS的QQ环境中）
			this.wakeupOrInstall()
		}
	}, data); //初始化时传入data，作为一键拉起/App传参安装时候的参数
}
// // 唤起App
export function openAppULink(id, data, urlAndroid, selector) {
	// data: { sharerId: '', href: '', shareDataId: '' }
	data.href = window.location.href
	const bwlink = base64encode(JSON.stringify(data))
	recordOpenApp({
		"clickLink": window.location.href,
		"promoteContent": bwlink,
		sharerId: data.sharerId
	})
	window.ULink([{
		id: id, //后台生成的裂变活动LinkID
		data: {
			bwlink
		}, //传递的自定义动态参数
		selector: selector ? selector : '#btn', //按钮的名称 //可选高级功能，具体含义请看下方U-Link API文档
		auto: true,
		timeout: 500,
		lazy: false,
		downloadUrl: urlAndroid,
		useOpenInBrowerTips: "default",
		proxyOpenDownload: (defaultAction, LinkInstance) => {
			// console.log('proxyOpenDownload', defaultAction, LinkInstance)
			// let overBox = null
			if (LinkInstance.solution.type === "scheme") {
				// qq或者微信环境特殊处理下
				if (window.ULink.isWechat || window.ULink.isQQ) {
					// 在qq或者微信环境执行内置逻辑，具体内置逻辑为:当设置了useOpenInBrowerTips字段时，qq&&微信&&scheme时，启用蒙层提示去浏览器打开
					defaultAction();
				} else {
					const downloadUrl = LinkInstance.solution.downloadUrl
					if (downloadUrl.indexOf('apple.com') != -1) {
						window.location.href = downloadUrl;
					} else {
						window.location.href = urlAndroid
					}
				}
			} else if (LinkInstance.solution.type === "universalLink") {
				console.log('universalLink', LinkInstance.solution.downloadUrl)
				if (window.ULink.isWechat || window.ULink.isQQ) {
					let overBox = document.createElement('view')
					let imgBox = document.createElement('img')
					imgBox.src = 'https://ebc-prod.cdn.benwunet.com/uni-static/img3.3.0/browser.png'
					overBox.style.background = 'rgba(0,0,0,0.8)'
					overBox.style.position = 'fixed'
					overBox.style.display = 'flex'
					overBox.style['justify-content'] = 'center'
					overBox.style.width = '100%'
					overBox.style.height = '100%'
					overBox.style.left = 0
					overBox.style.top = 0
					overBox.style['z-index'] = 10000
					imgBox.style.width = '85%'
					imgBox.style.height = '180px'
					overBox.appendChild(imgBox)
					document.querySelector("body").appendChild(overBox);
					overBox.onclick = function() {
						overBox.remove()
					}
				}

				// universalLink 唤起应当由服务端提供一个带重定向到appstore的universallink地址。因此，此处不应写逻辑，友盟会在近期上线universalLink 重定向功能。
				// window.location.href = LinkInstance.solution.downloadUrl
			}
		}
	}])
}

// 重置名单内容文本
export const whiteUrlCon = (con)=>{
	let text = con;
	const { bw_config } = getApp().getBWData(['bw_config']);
	const urls = con.match(
		/(https?|http)(:\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|])/g
	);
	if (urls && urls.length) {
		bw_config.domainWhitelist.filter((item) => {
			if (text.includes(item) && !text.includes("<a style='color:#E8CDA7'")) {
				const a = `(https?|http)(:\/\/.*${item}[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|])`;
				const regx = new RegExp(a, 'g');
				text = text.replace(regx, "<a style='color:#E8CDA7' href='$1$2'>$1$2</a>");
			}
		});
	}
	return text;
}
// 设置缓存，获取缓存
export const storageCommon = (data)=> {
	// name, type, value
	let returnData = ''
	if(typeof(data) == 'object'){
		const {name, type, value} = data
		if(type == 'set'){
			uni.setStorageSync(name, value);
		}else if(type == 'get'){
			returnData = uni.getStorageSync(name);
		}else if(type == 'sessionSet'){
			sessionStorage.setItem(name, value);
		}else if(type == 'sessionGet'){
			returnData = sessionStorage.getItem(name);
		}
	}else{
		returnData = uni.getStorageSync(data) || sessionStorage.getItem(data);
	}
	return returnData
}

